package com.yuntsg.ruiijn.controller.user;


import cn.hutool.core.io.FileUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.front.entity.Employee;
import com.yuntsg.nnsfcp.service.CommonService;
import com.yuntsg.ruiijn.database.entity.TextSelfDb;
import com.yuntsg.ruiijn.database.entity.UnitDept;
import com.yuntsg.ruiijn.database.entity.WosBasic;
import com.yuntsg.ruiijn.database.mapper.TextSelfDbMapper;
import com.yuntsg.ruiijn.database.mapper.UnitDeptMapper;
import com.yuntsg.ruiijn.database.mapper.WosBasicMapper;
import com.yuntsg.ruiijn.paperana.service.MatchService;
import com.yuntsg.ruiijn.paperana.utils.SmallTool;
import com.yuntsg.ruiijn.service.ManualCheckService;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import common.proxy.HttpUtil;
import common.util.*;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.*;

import static com.yuntsg.ruiijn.service.AsyncService.localDateFilePath;

@RestController
@RequestMapping("upload_local_file")
@Slf4j
@SuppressWarnings("ALL")
//@Api(tags = "单位信息相关")
public class UploadLocalFileController {
    @Value("${upload.path}")
    public String uploadPath;
    @Value("${upload.resultPath}")
    public String resultPath;
    @Resource
    ManualCheckService manualCheckService;
    @Resource
    CommonService commonService;
    @Resource
    DownloadUtil downloadUtil;
    @Resource
    HttpServletRequest request;
    @Resource
    TextSelfDbMapper textSelfDbMapper;
    @Resource
    UserUtil userUtil;
    @Resource
    MatchService matchService;
    @Autowired
    private UnitDeptMapper unitDeptMapper;
    @Autowired
    private WosBasicMapper wosBasicMapper;


//    @Resource
//    MatchService matchService;

    @GetMapping("/redopaperar")
    public ResultBean<Object> redopaperar(Integer id, Integer force) {
        //重新开始比对自定义文字开始
        log.info("重新开始比对自定义文字开始");
        CheckUtil.check(StringUtil.isNotNull(id), "id不能为空");
        int loginIdAsInt = userUtil.getUid();
        matchService.manualData(id, force);
        return new ResultBean<>();
    }

    // 下载文字报告特殊 只需要输入id
    @SneakyThrows
    @GetMapping("/downTextRe")
    public void downTextRe(Integer id) {
        //重新开始比对自定义文字开始
        log.info("下载报告开始");
        CheckUtil.check(StringUtil.isNotNull(id), "id不能空");
        WosBasic wosBasic = wosBasicMapper.selectById(id);
        String resultWord = wosBasic.getResultWord();
        CheckUtil.check(StringUtil.isNotNull(resultWord), "等待报告生成");
        String realPath = resultPath + resultWord;

        if (wosBasic.getCTi().contains("___")) {
            wosBasic.setCTi(wosBasic.getCTi().split("___")[1]);
        }
        String resWord = wosBasic.getCTi().toLowerCase().replace(".docx", "").replace(".pdf", "").replace("dox", "") + ".docx";
        downloadUtil.downloadWithFileName(realPath, resWord);
    }

    @GetMapping("/del-temp-txt-folder")
    public ResultBean<Object> del(String PATH) {
        if (StringUtil.isNull(PATH)) {
            return new ResultBean<>();
        }
        if (!PATH.equals("adasdwqdadadsasrfadwad2347671236756@%")) {
            return new ResultBean<>();
        }
        String path = "/home/analysis/comparepdftemp/";
        List<File> allPathDic = FileUtils.getAllPathDic(path);
        for (File file1 : allPathDic) {
            FileUtil.del(file1);
        }
        return new ResultBean<>("succ");
    }

    //    @ApiOperation(value = "01-查看能选择的导师列表")
//    @GetMapping("select")
//    public ResultBean<Object> select(Integer page, Integer limit) {
//        Page<SysUser> sysUserPage = new LambdaQueryChainWrapper<>(userMapper).select(SysUser::getId, SysUser::getRealName, SysUser::getPhone).eq(SysUser::getPermission, 2).page(new Page<>(page, limit));
//        return new ResultBean<>(sysUserPage);
//    }

    //    @ApiOperation(value = "查看我的文字自建库1")
    @GetMapping("/get-my-self-text-db")
    public ResultBean<Object> getMySelfTextDb(Integer page, Integer size) {
        if (StringUtil.isNull(page) || StringUtil.isNull(size)) {
            page = 1;
            size = 10;
        }
        IPage iPage = new Page(page, size);
        Integer uid = userUtil.getUid();
        IPage iPage1 = textSelfDbMapper.selectPage(iPage, new QueryWrapper<TextSelfDb>().eq("uid", uid).orderByDesc("id"));
        return new ResultBean<>(iPage1);
    }

    //    @ApiOperation(value = "查看我的文字自建库1前台使用")
    @GetMapping("/get-my-self-text-db-front")
    public ResultBean<Object> getMySelfTextDbFront(Integer page, Integer limit) {
        if (StringUtil.isNull(page) || StringUtil.isNull(limit)) {
            page = 1;
            limit = 10;
        }
        IPage iPage = new Page(page, limit);
        Integer uid = userUtil.getUid();
        IPage iPage1 = textSelfDbMapper.selectPage(iPage, new QueryWrapper<TextSelfDb>().eq("uid", uid).orderByDesc("id").eq("ins_sta", 1));
        return new ResultBean<>(iPage1);
    }

    @PostMapping("/add-my-self-text-db")
//    @ApiOperation(value = "添加到我的自定义文字库2")
    public ResultBean<Object> addMySelfText(String path) {
        CheckUtil.check(StringUtil.isNotNull(path), "路径不能空");
        String[] split = path.split("###");
        for (String s : split) {
            commonService.delAddMySelfTextDb(s);
        }
        return new ResultBean<>();
    }

    @GetMapping("/extra-my-self-text-db")
//    @ApiOperation(value = "解析到自建库3")
    public ResultBean<Object> extraMySelfText(Integer id) {
        CheckUtil.check(StringUtil.isNotNull(id), "id不能空");
        TextSelfDb textSelfDb = textSelfDbMapper.selectById(id);
        CheckUtil.check(StringUtil.isNotNull(textSelfDb), "非法请求");
//        CheckUtil.check(textSelfDb.getUid().equals(userUtil.getUid()), "非法操作");
        CheckUtil.check(textSelfDb.getInsSta() != 1, "已入库,重复入库");
        commonService.extraInfo(textSelfDb);
        return new ResultBean<>();
    }

    @GetMapping("/del-my-self-text-db")
//    @ApiOperation(value = "删除到自建库4")
    public ResultBean<Object> delMySelfText(Integer id) {
        CheckUtil.check(StringUtil.isNotNull(id), "id不能空");
        TextSelfDb textSelfDb = textSelfDbMapper.selectById(id);
        CheckUtil.check(StringUtil.isNotNull(textSelfDb), "非法请求");
//        CheckUtil.check(textSelfDb.getUid().equals(userUtil.getUid()), "非法操作");
//        CheckUtil.check(textSelfDb.getDel() != 1, "非法删除操作");
        commonService.delInfo(textSelfDb);
        return new ResultBean<>();
    }

    @PostMapping("/del-my-self-text-db-real")
//    @ApiOperation(value = "真实删除到自建库5")
    public ResultBean<Object> delMySelfTextReal(String id) {
        CheckUtil.check(StringUtil.isNotNull(id), "id不能空");
        String[] split = id.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Integer.parseInt(s));
        }
        for (Integer i : ids) {
            TextSelfDb textSelfDb = textSelfDbMapper.selectById(i);
            CheckUtil.check(StringUtil.isNotNull(textSelfDb), "非法请求");
//            CheckUtil.check(textSelfDb.getUid().equals(userUtil.getUid()), "非法操作");
            commonService.delInfo(textSelfDb);
            commonService.delInfoUpTableRecord(textSelfDb);
            textSelfDbMapper.deleteById(textSelfDb.getId());
        }
        return new ResultBean<>();
    }

    @GetMapping("/del-my-self-text-db-all-real")
//    @ApiOperation(value = "一键清空自建库内容真实删除到自建库6")
    public ResultBean<Object> delMySelfTextAllReal() {
        List<TextSelfDb> textSelfDbs = textSelfDbMapper.selectList(new QueryWrapper<TextSelfDb>().eq("uid", userUtil.getUid()));
        for (TextSelfDb textSelfDb : textSelfDbs) {
            CheckUtil.check(StringUtil.isNotNull(textSelfDb), "非法请求");
//            CheckUtil.check(textSelfDb.getUid().equals(userUtil.getUid()), "非法操作");
            commonService.delInfo(textSelfDb);
            commonService.delInfoUpTableRecord(textSelfDb);
            textSelfDbMapper.deleteById(textSelfDb.getId());
        }
        return new ResultBean<>("一键清除完毕");
    }


    //    @ApiOperation(value = "02-本地文献模块,上传各类文件")
    @GetMapping("upload_local_file")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pushFlag", value = "是否已发表"),
//            @ApiImplicitParam(name = "spilt", value = "上传的图片是否需要拆分 0 不拆分  1 拆分 "),
//            @ApiImplicitParam(name = "deptId", value = "科室ID,当前文章在哪个科室下"),
//            @ApiImplicitParam(name = "path", value = "先调用上传接口 上传接口返回文件路径后当做参数带回到这里"),
//            @ApiImplicitParam(name = "path2", value = "自定义文本对比第二个文档,入库es 根据fid 和uid 进行区分查询 不入记录表-gcr"),
//            @ApiImplicitParam(name = "annex", value = "附件"),
//            @ApiImplicitParam(name = "content", value = "pmid/ut/doi"),
//            @ApiImplicitParam(name = "context", value = "自定义对比用的上传文本-gcr"),
//            @ApiImplicitParam(name = "selfTxt", value = "文字对比库 0 是全网 1是自建库-gcr"),
//            @ApiImplicitParam(name = "txtComIds", value = "自定义对比文字库选择的id 集合 可以null "),
//            @ApiImplicitParam(name = "simi", value = "自定义对比用 相似度-gcr"),
//            @ApiImplicitParam(name = "master", value = "导师"),
//            @ApiImplicitParam(name = "author", value = "归属作者"),
//            @ApiImplicitParam(name = "belongDate", value = "归属日期"),
//            @ApiImplicitParam(name = "title", value = "文章标题"),
//            @ApiImplicitParam(name = "fileType", value = "2 PDF  3 WORD  4 图片 "),
//            @ApiImplicitParam(name = "splitType", value = "1 只要图片 2 只要文字 3 图文  4 国自然数据")
//    })
    public ResultBean<Object> upload_pdf_local(Integer pushFlag,
                                               Integer split,
                                               Integer deptId,
                                               String path,
                                               String path2,
                                               String annex,
                                               String content,
                                               String context,
                                               String selfTxt,
                                               String txtComIds,
                                               String simi,
                                               Integer masterId,
                                               String master,
                                               String author,
                                               String belongDate,
                                               String title,
                                               Integer fileType,
                                               Integer splitType, Integer bidID
    ) {


        /**
         * 如果是多个PDF上传
         */
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String s = parameterNames.nextElement();
            String parameter = request.getParameter(s);
            System.out.println(s);
            System.out.println(parameter);
            System.out.println("+++++++++++++++++++++");


        }

        log.info("selftxt+" + selfTxt);
        if (fileType != null && fileType == 2) {
            if (path.contains("#P#D#F#")) {
                String pdfPath = localDateFilePath() + "MERGE_" + System.currentTimeMillis() + ".PDF";
                String[] paths = path.split("#P#D#F#");
                List<String> strings = Arrays.asList(paths);
                List<String> list = new ArrayList<>();
                for (String string : strings) {
                    list.add(uploadPath + string);
                }
                boolean succ = PDFMERGE.mergePdfFiles(list, uploadPath + pdfPath);
                if (succ) {
                    path = pdfPath;
                } else {
                    return new ResultBean<>(3, "多文件PDF合并错误");
                }
            }
        }

        /**
         * 如果已经填写了PMID/DOI/UT 则需要给他们获取全文
         */
        String orgcontent = content;
        if (null != content) {
            boolean nextFlag = false;
            if (content.length() > 20) {
                //  10.2174/1573405618666220415122843 这样的doi 填写不了啊 超过20位了  我先注释掉了 gcr
//                return new ResultBean<>(3, "请正确填写pmid/doi/ut号,请选择一种补充");
            }
            if (content.contains("doi:") || content.startsWith("10.")) {
                try {
                    content = content.toLowerCase().replaceAll("doi:", "").trim();
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("term", URLEncoder.encode(content, "utf-8"));
                    String result = HttpRequest.post("http://165.140.240.249:808/pm-newsearch.php").header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                            .form(paramMap)//表单内容
                            .timeout(30000)//超时，毫秒
                            .execute().body();
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    if (jsonObject.get("type").equals(1)) {
                        JSONObject info = JSONUtil.parseObj(JSONUtil.parseArray(jsonObject.getStr("list")).get(0));
                        String pmid = info.getStr("pmid");
                        if (null != pmid) {
                            content = pmid;
                            log.info("根据 DOI 获取到的 PMID 是___" + content);
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
        /**
         * 获取上传人
         */
        int loginIdAsInt = userUtil.getUid();
        Integer logid = loginIdAsInt;
        Employee sysUser = userUtil.getUserEmployee();
        WosBasic wosBasic = new WosBasic();
        wosBasic.setUploadName(sysUser.getUserName());
        wosBasic.setTxtComIds(txtComIds);
        wosBasic.setUid(sysUser.getId());
        wosBasic.setGid(userUtil.getGid());
        wosBasic.setAuthor(author);
        wosBasic.setBidId(bidID);
        wosBasic.setMaster(master);
        wosBasic.setMasterId(masterId);
        wosBasic.setBelongDate(belongDate);
        wosBasic.setDeptName("dept");
        if (StringUtil.isNotNull(selfTxt)) {
            wosBasic.setSelfTxt(Integer.parseInt(selfTxt));
        }
        wosBasic.setDeptId(deptId);
        log.info("额外处理获取ut号获取处理过之前的的pmid 是+" + orgcontent);
        //进行获取我的情况查询ut号码
        if (StringUtil.isNotNull(orgcontent)) {
            if (orgcontent.contains("doi:") || orgcontent.startsWith("10.")) {
                String getut = manualCheckService.getut(orgcontent);
                String getdoiTimeYear = manualCheckService.getdoiTimeYear(orgcontent);
                log.info("通过我的方法获取ut号是" + getut);
                log.info("通过我的方法获取发表时间是" + getdoiTimeYear);
                if (StringUtil.isNotNull(getut)) {
                    wosBasic.setCUt(getut);
                }
                if (StringUtil.isNotNull(getdoiTimeYear)) {
                    wosBasic.setCPy(getdoiTimeYear);
                }
            }
        }

        try {
            if (StringUtil.isNull(wosBasic.getCPm())) {
                if (content.length() >= 7 && content.length() <= 8) {
                    log.info("存入了pm+" + content);
                    // 需要加入ut  因为有的文章在pm库也在ut 需要都排除下
                    String getpmutmatch = manualCheckService.getpmutmatch(content);
                    if (StringUtil.isNull(wosBasic.getCUt()) && StringUtil.isNotNull(getpmutmatch)) {
                        log.info("存入了pm 对应的ut+" + getpmutmatch);
                        wosBasic.setCUt(getpmutmatch);
                    }

                    wosBasic.setCPm(content);
                }
            }
            if (StringUtil.isNull(wosBasic.getCUt())) {
                if (content.length() >= 14 && content.length() <= 15) {
                    log.info("存入了ut+" + content);
                    String getpmutmatch = manualCheckService.getpmutmatch(content);
                    if (StringUtil.isNull(wosBasic.getCPm()) && StringUtil.isNotNull(getpmutmatch)) {
                        log.info("存入了ut 对应的pm+" + getpmutmatch);
                        wosBasic.setCPm(getpmutmatch);

                    }
                    wosBasic.setCUt(content);
                }
            }
            if (StringUtil.isNull(wosBasic.getCPy())) {
                Integer pmut = 2;
                if (content.length() == 14 || content.length() == 15) {
                    pmut = 1;
                }
                Integer selfArtYear = ManualCheckService.getpmutYear(content, pmut);
                if (StringUtil.isNotNull(selfArtYear)) {
                    log.info("设置了年份selfArtYear" + selfArtYear);
                    wosBasic.setCPy(selfArtYear + "");
                }
            }

        } catch (Exception e) {
        }
        wosBasic.setFileType(fileType);
        wosBasic.setFilePath(path);//
        wosBasic.setPdfUrl(getPdf(content));
        wosBasic.setCTi(title);
        wosBasic.setAnnex(annex);//附件
        wosBasic.setSplit(split);
        wosBasic.setAdmCheck(0);
        wosBasic.setSplitType(splitType);
        //如果是导师上传的,则只能管理员查看
//        if (sysUser.getPermission() == 2 || sysUser.getPermission() == 1) {
//            wosBasic.setAdmCheck(1);
//        }
        wosBasicMapper.insert(wosBasic);

        long start1 = System.currentTimeMillis();
        WosBasic wosBasic1 = wosBasicMapper.selectById(wosBasic.getId());
        // 文字拆分放在这里
        if (splitType != null && splitType == 2) {

            wosBasic1.setSoType(3);
            if (StringUtils.isNotEmpty(simi)) {
                wosBasic1.setSimi(simi);
            } else {
                log.info("没有传递默认传30相似度");
                wosBasic1.setSimi("30");
            }
            if (StringUtils.isNotEmpty(path2)) {
                Integer integer = manualCheckService.dealMulCheck(path, path2, author, title);
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(1);
            } else {
                Integer integer = 0;
                if (StringUtils.isEmpty(path)) {
                    integer = manualCheckService.dealSinCheck(0, context, author, title, path, content, logid);
                } else {
                    integer = manualCheckService.dealSinCheck(2, context, author, title, path, content, logid);
                }
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(0);
            }
        } else {

            if (splitType != null && splitType == 3) {
                log.info("前台走了下图文 进行文字拆分到表里面");
                Integer integer = 0;
                if (StringUtils.isEmpty(path)) {
                    integer = manualCheckService.dealSinCheck(0, context, author, title, path, content, logid);
                } else {
                    integer = manualCheckService.dealSinCheck(2, context, author, title, path, content, logid);
                }
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(0);
            }
            wosBasic1.setSoType(2);
        }
        wosBasicMapper.updateById(wosBasic1);
        SmallTool.printMessLongTimeTake("拆分测试耗时+", start1);
        //发送邮件
        //sendEmail(author, FileUtil.file(uploadPath + path));
//        sysUser.setUploadCount(sysUser.getUploadCount() + 1);
        wosBasic.setUploadName(sysUser.getUserName());
//        sysUserMapper.updateById(sysUser);

        return new ResultBean<>("操作成功");
    }

    /**
     * 获取全文路径
     *
     * @param content
     * @return
     */
    public String getPdf(String content) {
        if (StringUtil.isEmpty(content)) {
            return null;
        }

        String abase64 = "";
        String newLink = "";
        String url = "";
        if (content.length() <= 8 && !content.startsWith("10.")) {
            abase64 = XXTEA.encryptToBase64StringNoSafe(content, "R0HWlCI3ndd1s8S3");
            url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=0&query=" + abase64;
        } else {
            abase64 = XXTEA.encryptToBase64StringNoSafe(content.toUpperCase().replaceAll("WOS:", "").trim(), "R0HWlCI3ndd1s8S3");
            url = "https://www.pubtsg.com/api/getpdfurl.do?unitid=1&type=1&query=" + abase64;
        }
        BasicCookieStore cookieStore = new BasicCookieStore();
        String html = HttpUtil.postHtmlQuanWen(cookieStore, url, "", "");

        Map<String, Object> map = new HashMap<String, Object>();
        map = JSON.parseObject(html, Map.class);
        if (map.get("pdfurl") != null) {
            String pdfUrl = (String) map.get("pdfurl");
            return pdfUrl;
        }
        return null;
    }
}
